<template>
  <div class="notifications-page">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-container">
        <!-- Logo和标题 -->
        <div class="logo-section" @click="goToHome" style="cursor: pointer;">
          <img src="../../assets/images/login/logo2.png" class="logo-image" />
          <span class="logo-text">云启国际人才港</span>
        </div>
        
        <!-- 导航菜单 -->
        <nav class="nav-menu">
          <div
            v-for="(item, index) in navItems"
            :key="index"
            class="nav-item"
            :class="{ active: item.active }"
            @click="handleNavClick(item)"
            >
              {{ item.name }}
          </div>
        </nav>
        
        <!-- 右侧按钮 -->
        <div class="header-buttons">
          <!-- 登录状态下显示用户操作按钮 -->
          <div v-if="isLoggedIn" class="user-actions">
            <!-- <el-icon class="notification-bell" size="20" @click="goToNotifications"><Bell /></el-icon> -->
            <span class="action-item" @click="handleDropdownCommand(userType === 'enterprise' ? 'enterprise-center' : 'user-center')">
              {{ userType === 'enterprise' ? t('userHome.enterpriseCenter') : t('userHome.personalCenter') }}
            </span>
            <span class="action-item" @click="handleDropdownCommand('logout')">退出</span>
          </div>
          
          <!-- 未登录状态下显示登录按钮 -->
          <el-button
            v-else
            type="primary"
            class="btn-login"
            @click="handleLogin"
          >
            登录
          </el-button>
        </div>
      </div>
    </header>

    <!-- 三列布局主内容区域 -->
    <div class="three-column-layout">
      <!-- 左侧列 -->
      <aside class="left-column">
        <div class="left-content">
          <!-- 左侧内容已清空 -->
        </div>
      </aside>

      <!-- 中间列 -->
      <main class="center-column">
        <div class="page-header">
          <div class="breadcrumb">
            <span class="breadcrumb-item">首页</span>
            <span class="breadcrumb-separator">>></span>
            <span class="breadcrumb-item active">公告</span>
          </div>
        </div>

        <div class="main-content-wrapper">
          <div class="notifications-content">
            <div v-if="selectedAnnouncement" class="announcement-detail">
              <div class="detail-header">
                <h2 class="detail-title">{{ selectedAnnouncement.title }}</h2>
                <div class="detail-meta">
                  <span class="meta-item">
                    <el-icon><User /></el-icon>
                    {{ selectedAnnouncement.authorName }}
                  </span>
                  <span class="meta-item">
                    <el-icon><Calendar /></el-icon>
                    {{ formatTime(selectedAnnouncement.publishTime) }}
                  </span>
                  <span class="meta-item">
                    <el-icon><Collection /></el-icon>
                    {{ selectedAnnouncement.category }}
                  </span>
                  <span v-if="selectedAnnouncement.isTop" class="top-indicator">
                    <el-icon><Star /></el-icon>
                    置顶
                  </span>
                </div>
              </div>
              <div class="detail-content" v-html="selectedAnnouncement.content"></div>
            </div>
            <div v-else class="no-selection">
              <el-icon class="no-selection-icon"><Document /></el-icon>
              <p>请选择一条公告查看详情</p>
            </div>
          </div>
        </div>
      </main>

      <!-- 右侧列 -->
      <aside class="right-column">
        <div class="right-content">
          <h3>公告列表</h3>
          
          <!-- 搜索框 -->
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索公告..."
              clearable
              @input="handleSearch"
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          
          <!-- 公告列表 -->
          <div class="announcement-list">
            <div v-if="loading" class="loading-state">
              <el-icon class="is-loading"><Loading /></el-icon>
              <span>加载中...</span>
            </div>
            
            <div v-else-if="announcementList.length === 0" class="empty-state">
              <el-icon><Document /></el-icon>
              <span>暂无公告</span>
            </div>
            
            <div 
              v-else
              v-for="announcement in announcementList" 
              :key="announcement.articleId" 
              class="announcement-item"
              :class="{ 'is-top': announcement.isTop, 'is-selected': selectedAnnouncement && selectedAnnouncement.articleId === announcement.articleId }"
              @click="selectAnnouncement(announcement)"
            >
              <div class="announcement-title">
                <span v-if="announcement.isTop" class="top-badge">【置顶】</span>
                {{ announcement.title }}
              </div>
              <div class="announcement-meta">
                <span class="category">{{ announcement.category }}</span>
                <span class="publish-time">{{ formatTime(announcement.publishTime) }}</span>
              </div>
            </div>
          </div>
          
          <!-- 分页指示器 -->
          <div v-if="totalPages > 1" class="pagination-dots">
            <span 
              v-for="page in totalPages" 
              :key="page"
              class="dot"
              :class="{ active: currentPage === page }"
              @click="goToPage(page)"
            ></span>
          </div>
          
          <!-- 分页信息 -->
          <div class="pagination-info">
            <span>共 {{ total }} 条公告</span>
            <span>第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
          </div>
        </div>
      </aside>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import { Bell, Search, Loading, Document, User, Calendar, Collection, Star } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { useAuth } from '../../composables/useAuth'
import request from '../../utils/request'

const router = useRouter()
const { t } = useI18n()
const { userType } = useAuth()

// 根据用户角色动态设置导航菜单
const navItems = computed(() => {
  if (userType.value === 'enterprise') {
    // 企业用户导航菜单
    return [
      { name: t('userHome.home'), active: false, route: '/henterprise/home' },
      { name: t('userHome.talentPool'), active: false, route: '/code/enterprise/talent-search' },
      { name: t('userHome.applicationRecords'), active: false, route: '/code/enterprise/applications' }
    ]
  } else {
    // 学生用户导航菜单
    return [
      { name: t('userHome.home'), active: false, route: '/use/home' },
      { name: t('userHome.demandLibrary'), active: false, route: '/use/enterprise-demand' },
      { name: t('userHome.applicationRecords'), active: false, route: '/applications' }
    ]
  }
})

// 登录状态
const { isLoggedIn } = useAuth()

// 公告列表相关数据
const announcementList = ref([])
const currentPage = ref(1)
const totalPages = ref(1)
const total = ref(0)
const searchKeyword = ref('')
const pageSize = 10
const loading = ref(false)
const selectedAnnouncement = ref(null)

// 获取公告列表
const fetchAnnouncements = async (page = 1, keyword = '') => {
  loading.value = true
  try {
    const response = await request.get('/api/student/notice/list', {
      params: {
        page: page,
        size: pageSize,
        category: '', // 分类筛选传入空值
        keyword: keyword || ''
      }
    })
    
    if (response.code === 200) {
      const data = response.data
      announcementList.value = data.articles || []
      totalPages.value = data.totalPages || 1
      total.value = data.total || 0
      currentPage.value = page
      
      // 自动选择默认公告：优先选择置顶公告，如果没有则选择最新公告
      if (announcementList.value.length > 0) {
        const topAnnouncement = announcementList.value.find(item => item.isTop)
        const defaultAnnouncement = topAnnouncement || announcementList.value[0]
        await selectAnnouncement(defaultAnnouncement)
      }
    } else {
      ElMessage.error(response.message || '获取公告列表失败')
      announcementList.value = []
      totalPages.value = 1
      total.value = 0
    }
  } catch (error) {
    console.error('获取公告列表失败:', error)
    ElMessage.error('获取公告列表失败，请稍后重试')
    announcementList.value = []
    totalPages.value = 1
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 选择公告
const selectAnnouncement = async (announcement) => {
  try {
    const response = await request.get(`/api/student/notice/${announcement.articleId}`)
    if (response.code === 200) {
      selectedAnnouncement.value = response.data
    } else {
      ElMessage.error(response.message || '获取公告详情失败')
    }
  } catch (error) {
    console.error('获取公告详情失败:', error)
    ElMessage.error('获取公告详情失败，请稍后重试')
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  selectedAnnouncement.value = null
  fetchAnnouncements(1, searchKeyword.value)
}

// 分页跳转
const goToPage = (page) => {
  if (page !== currentPage.value && page >= 1 && page <= totalPages.value) {
    selectedAnnouncement.value = null
    fetchAnnouncements(page, searchKeyword.value)
  }
}

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return ''
  try {
    const date = new Date(timeString)
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    })
  } catch (error) {
    return timeString
  }
}

// 监听搜索关键词变化，防抖处理
let searchTimer = null
watch(searchKeyword, (newVal) => {
  if (searchTimer) {
    clearTimeout(searchTimer)
  }
  searchTimer = setTimeout(() => {
    handleSearch()
  }, 500)
})

// 页面加载时获取公告列表
onMounted(() => {
  // 同步登录状态
  const { syncAuth } = useAuth()
  syncAuth()
  
  // 获取公告列表
  fetchAnnouncements()
})

// 导航点击处理
const handleNavClick = (item) => {
  navItems.value.forEach(nav => nav.active = false)
  item.active = true
  router.push(item.route)
}

// 返回首页
const goToHome = () => {
  if (userType.value === 'enterprise') {
    // 企业用户跳转到企业首页
    router.push('/henterprise/home')
  } else {
    // 学生用户跳转到学生首页
    router.push('/use/home')
  }
}

// 跳转到通知页面
const goToNotifications = () => {
  router.push('/code/enterprise/notifications')
}

// 处理下拉菜单命令
const handleDropdownCommand = (command) => {
  switch (command) {
    case 'enterprise-center':
      router.push('/code/enterprise/space')
      break
    case 'user-center':
      router.push('/profile')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 退出登录
const { logout } = useAuth()
const handleLogout = () => {
  logout()
  ElMessage.success('已退出登录')
}

// 登录处理
const handleLogin = () => {
  // 根据当前路径判断跳转到哪个登录页面
  if (window.location.pathname.includes('/use/')) {
    router.push('/xueshengdenglu')
  } else {
    router.push('/qiyedenglu')
  }
}
</script>

<style scoped>
.notifications-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 顶部导航栏样式 */
.header {
  background-color: #ffffff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  height: 64px;
}

.logo-section {
  display: flex;
  align-items: center;
  gap: 12px;
  transition: all 0.3s ease;
}

.logo-section:hover {
  transform: scale(1.02);
  opacity: 0.8;
}

.logo-image {
  width: 40px;
  height: 40px;
  object-fit: contain;
}

.logo-text {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.nav-menu {
  display: flex;
  gap: 32px;
}

.nav-item {
  padding: 8px 16px;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.3s ease;
  color: #666;
}

.nav-item:hover {
  color: #409eff;
  background-color: #f0f9ff;
}

.nav-item.active {
  color: #409eff;
  background-color: #f0f9ff;
}

.header-buttons {
  display: flex;
  align-items: center;
  gap: 16px;
}

.user-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.notification-bell {
  cursor: pointer;
  color: #666;
  transition: color 0.3s ease;
}

.notification-bell:hover {
  color: #409eff;
}

.action-item {
  cursor: pointer;
  color: #666;
  transition: color 0.3s ease;
}

.action-item:hover {
  color: #409eff;
}

.btn-login {
  background-color: #409eff;
  border-color: #409eff;
}

/* 三列布局样式 */
.three-column-layout {
  display: flex;
  justify-content: center;
  gap: 24px;
  padding: 24px;
  min-height: calc(100vh - 64px); /* 减去header高度 */
}

.left-column {
  flex: 1;
  padding: 24px;
  min-height: 400px;
  background: none;
  box-shadow: none;
  border-radius: 0;
}

.right-column {
  flex: 1;
  padding: 24px;
  height: 800px;
  max-height: 800px;
  overflow: hidden;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-top: 64px; /* 与main-content-wrapper顶部对齐，64px是page-header的高度 */
  position: sticky;
  top: 64px; /* 顶部导航栏的高度 */
}

.left-content,
.right-content {
  padding: 0;
}

.left-content h3,
.right-content h3 {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #eee;
}

.left-content p,
.right-content p {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
}

/* 公告详情样式 */
.announcement-detail {
  padding: 0;
}

.detail-header {
  margin-bottom: 24px;
}

.detail-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0 auto 16px auto;
  line-height: 1.4;
  width: 50%;
  text-align: center;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.detail-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  align-items: center;
  font-size: 14px;
  color: #666;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
}

.meta-item .el-icon {
  font-size: 16px;
  color: #999;
}

.top-indicator {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #409eff;
  font-weight: 500;
}

.top-indicator .el-icon {
  color: #409eff;
}

.detail-content {
  font-size: 16px;
  line-height: 1.8;
  color: #333;
}

.detail-content h2,
.detail-content h3 {
  color: #333;
  margin: 24px 0 16px 0;
}

.detail-content h2 {
  font-size: 20px;
  font-weight: 600;
}

.detail-content h3 {
  font-size: 18px;
  font-weight: 500;
}

.detail-content p {
  margin: 16px 0;
}

.detail-content ul {
  margin: 16px 0;
  padding-left: 24px;
}

.detail-content li {
  margin: 8px 0;
}

/* 无选择状态样式 */
.no-selection {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80px 0;
  color: #999;
  text-align: center;
}

.no-selection-icon {
  font-size: 64px;
  margin-bottom: 16px;
  color: #ddd;
}

.no-selection p {
  font-size: 16px;
  margin: 0;
}

/* 搜索框样式 */
.search-box {
  margin-bottom: 16px;
}

.search-box .el-input {
  width: 100%;
}

/* 公告列表样式 */
.announcement-list {
  margin-top: 16px;
  max-height: 500px;
  overflow-y: auto;
}

/* 加载状态样式 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #999;
  font-size: 14px;
}

.loading-state .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
  color: #409eff;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
  color: #999;
  font-size: 14px;
}

.empty-state .el-icon {
  font-size: 48px;
  margin-bottom: 12px;
  color: #ddd;
}

.announcement-item {
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.3s ease;
}

.announcement-item:last-child {
  border-bottom: none;
}

.announcement-item:hover {
  padding-left: 8px;
  padding-right: 8px;
  margin-left: -8px;
  margin-right: -8px;
  border-radius: 6px;
}

.announcement-item.is-top {
  border-left: 3px solid #409eff;
  padding-left: 13px;
}

.announcement-item.is-selected {
  background-color: #e6f7ff;
  border-left: 3px solid #409eff;
  padding-left: 13px;
}

.announcement-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  line-height: 1.5;
  margin-bottom: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.top-badge {
  color: #fa8c16;
  font-weight: 600;
  margin-right: 4px;
}

.announcement-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #999;
}

.category {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 11px;
}

.publish-time {
  color: #999;
}

/* 分页指示器样式 */
.pagination-dots {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  margin: 20px 0 16px 0;
  padding: 16px 0;
  border-top: 1px solid #f0f0f0;
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #ddd;
  cursor: pointer;
  transition: all 0.3s ease;
}

.dot:hover {
  background-color: #409eff;
  transform: scale(1.2);
}

.dot.active {
  background-color: #409eff;
  transform: scale(1.2);
}

/* 分页信息样式 */
.pagination-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #999;
  padding: 12px 0;
  border-top: 1px solid #f0f0f0;
}

.center-column {
  width: 1200px;
  flex-shrink: 0; /* 防止中间列被压缩 */
}

.page-header {
  margin-bottom: 24px;
}

.breadcrumb {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #666;
  background-color: #ffffff;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.breadcrumb-item {
  cursor: pointer;
  transition: color 0.3s ease;
}

.breadcrumb-item:hover {
  color: #409eff;
}

.breadcrumb-item.active {
  color: #409eff;
  font-weight: 500;
}

.breadcrumb-separator {
  color: #ccc;
  margin: 0 4px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.main-content-wrapper {
  background-color: #ffffff;
  border-radius: 8px;
  padding: 24px;
  min-height: 400px;
}

.notifications-content {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  font-size: 16px;
  min-height: 300px;
  padding-bottom: 200px; /* 底部延伸高度 */
}
</style> 